import 'package:flutter/material.dart';
import 'package:safety_platform/models/hidden_danger.dart';
import 'package:safety_platform/models/situation.dart';
import 'package:safety_platform/models/attachment.dart';
import 'package:safety_platform/components/hidden_danger.dart';
import 'package:safety_platform/components/button.dart';
import 'package:safety_platform/pages/services.dart'
    show uploadAttachment, submitHiddenDangerDone;
import 'package:safety_platform/components/attachment.dart' show AttachmentGallery;
import 'package:safety_platform/theme.dart' show backgroundTitle; 
import 'package:safety_platform/utils.dart' 
    show SelectionNode, openSingleSelectionDialog, showErrorDialog, showEditPopDialog;
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:file_picker/file_picker.dart';
import 'package:mime/mime.dart' show lookupMimeType;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:safety_platform/components/attachment.dart' show AttachmentPreviewGallery;

import 'dart:io';

class HiddenDangerExectionPage extends StatefulWidget {
  final HiddenDanger hiddenDanger;
  const HiddenDangerExectionPage({this.hiddenDanger});
  @override
  State<StatefulWidget> createState() =>
      _HiddenDangerExectionPageState(hiddenDanger: hiddenDanger);
}

class _HiddenDangerExectionPageState extends State<HiddenDangerExectionPage> {
  _HiddenDangerExectionPageState({
    this.hiddenDanger,
  });
  HiddenDanger hiddenDanger;
  final List<SelectionNode> uploadAttachmentMethod = new List();
  TextEditingController _controller;

  bool _submitting = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("整改结果"),
        elevation: 0,

        //     leading: appLeading(context),
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      body: SingleChildScrollView(child: _body()),
      bottomNavigationBar: _bottomVavigationBar(),
    );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    Situation situation = hiddenDanger.situations[index];
    List<Widget> children = [
      Flexible(
        flex: 1,
        child: Text(
          situation.content,
          // softWrap: false,
          overflow: TextOverflow.fade,
          maxLines: 8,
          style: Theme.of(context).textTheme.subhead,
        ),
      ),
    ];
    if (situation.improvement == null) {
      children.add(
        Padding(
          padding: EdgeInsets.symmetric(vertical: 8),
          child: InkWell(
            child: Text(
              '增加整改措施',
              style: TextStyle(
                color: Colors.blue,
              ),
            ),
            onTap: () => showEditPopDialog(
              context,
              _controller,
              '增加整改措施',
              '请输入整改措施，150字以内',
              ()  {
                if (_controller.text !=null && _controller.text.length>0) {
                  setState(() {
                   situation.improvement = _controller.text; 
                  });
                }
                _controller.clear();
              }
            ),
            // onTap: () => this._showPopDialog('增加整改措施', () {
            //       if (_controller.text != null && _controller.text.length > 0) {
            //         setState(() {
            //           situation.improvement = _controller.text;
            //         });
            //       }
            //       _controller.clear();
            //     }),
          ),
        ),
      );
    } else {
      children.add(Padding(
        padding: EdgeInsets.symmetric(vertical: 4),
        child: Text(
          '整改措施',
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: Theme.of(context).disabledColor,
          ),
        ),
      ));
      children.add(Text(situation.improvement,
          style: TextStyle(
            fontSize: 12,
            color: Theme.of(context).disabledColor,
          )));
    }
    return DecoratedBox(
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(
              width: 0.5,
              color: Color.fromARGB(251, 241, 241, 241),
            ))),
        child: Container(
          padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
          // height: 80,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: children,
          ),
        ));
  }

 

  void _takePhoto() {
    ImagePicker.pickImage(source: ImageSource.camera).then(
      (file) {
        Attachment attachment = Attachment.fromLocal(file.path, file.path);
        uploadAttachment(attachment, target: 'risk.RectifyAttachment').then(
          (Attachment attach) {
            setState(() {
               attachment.id  = attach.id;
            attachment.url = attach.url;
            attachment.uploadStatus = 'done';
            });
          }
        );
        setState(() {
          hiddenDanger.attachments.add(attachment) ;
        });
      }
    );
  }

  Widget _a() {
    Widget attachments = Container();
    print('ha ==>${hiddenDanger.attachments}');
   

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
            child: Text(
              '整改报告',
              style: TextStyle(
                fontWeight: FontWeight.w600,
              ),
            ),
            padding: EdgeInsets.fromLTRB(16, 8, 16, 8),),
        AttachmentGallery(
          attachments: hiddenDanger.attachments,
          uploadLabel: '上传整改报告图片',
          onTakePhoto: () =>_takePhoto(),
          backgoundColor: Colors.white,
        )
        // attachments,
        // DecoratedBox(
        //   decoration: BoxDecoration(
        //       color: Colors.white,
        //       border: Border(
        //           bottom: BorderSide(
        //               color: Color.fromARGB(255, 241, 241, 241), width: 0.5))),
        //   child: Row(
        //     // padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        //     children: [
        //       InkWell(
        //         onTap: () => _uploadAttachment(),
        //         child: Padding(
        //           padding: EdgeInsets.symmetric(horizontal: 8),
        //           child: FlatButton.icon(
        //             icon: Icon(
        //               Icons.cloud_upload,
        //               color: Theme.of(context).primaryColor,
        //             ),
        //             label: Text(
        //               '上传或拍摄整改报告',
        //               style: TextStyle(color: Theme.of(context).primaryColor),
        //             ),
        //           ),
        //         ),
        //       ),
        //     ],
        //   ),
        // ),
      ],
    );
  }

  Widget _t() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
              child: Text(
                '整改情况',
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                ),
              ),
              padding: EdgeInsets.fromLTRB(16, 8, 16, 8)),
          DecoratedBox(
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom: BorderSide(
                          color: Color.fromARGB(255, 241, 241, 241),
                          width: 0.5))),
              child: ListTile(
                title: Text('整改类型'),
                trailing: Text('内部整改'),
              )),
          DecoratedBox(
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                      bottom: BorderSide(
                          color: Color.fromARGB(255, 241, 241, 241),
                          width: 0.5))),
              child: Container(
                  padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                  child: Row(
                    children: <Widget>[
                      Expanded(flex: 2, child: Text('实际花费金额')),
                      Expanded(
                          flex: 1,
                          child: TextField(
                            textAlign: TextAlign.right,
                            textInputAction: TextInputAction.go,
                            keyboardType: TextInputType.number,
                            // inputFormatters: [

                            // ],
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: 0.toString(),
                            ),
                          )),
                      Padding(
                          child: Text('元'), padding: EdgeInsets.only(left: 8)),
                    ],
                  ))
              // trailing: SizedBox(
              //   child: TextField(),
              //   width: 80,
              //   height: 80,
              // ),
              ),
             
        ],
      ),
    );
  }

  Widget _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        HiddenDangerLiteWidget(hiddenDanger),
        backgroundTitle('存在的问题'),
     
        ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: hiddenDanger.situations.length,
          itemBuilder: (BuildContext context, int index) =>
              _itemBuilder(context, index),
        ),
         AttachmentPreviewGallery(
                attachments: hiddenDanger.situationImages,
                collapseLabel: '查看问题图片',
              ),
        _t(),
        _a()
      ],
    );
  }

  _comfirmedSubmit() {
    setState(() {
      _submitting = true;
    });

    submitHiddenDangerDone(hiddenDanger).then((HiddenDanger hiddenDanger) {
      Fluttertoast.showToast(msg: '提交成功');
      Navigator.of(context).pop(hiddenDanger);
      setState(() {
        _submitting = false;
      });
    });
  }

  _submit() {
    if (hiddenDanger.situations.any((Situation s) => s.improvement == null)) {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('请确认'),
              content: Text('还有存在的问题未提供整改措施，仍然提交？'),
              actions: <Widget>[
                FlatButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: Text('取消'),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    _comfirmedSubmit();
                  },
                  // textColor: Theme.of(context).primaryColor,
                  child: Text(
                    '确定',
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                    ),
                  ),
                )
              ],
            );
          });
      return;
    }
    if (hiddenDanger.attachments
        .any((Attachment attachment) => attachment.uploadStatus != 'done')) {
      showErrorDialog(context, '错误', '还有文件正在上传中，不能提交', () => {});
      return;
    }
    this._comfirmedSubmit();
  }

  _bottomVavigationBar() {
    // if (_task != null && _task.status == 'pending') {
    return Container(
        width: MediaQuery.of(context).size.width,
        height: 48,
        color: Colors.white,
        child: Button(
          loading: _submitting,
          buttonColor: Colors.white,
          onPressed: () {
            _submit();
            // _submit();
            // Navigator.of(context).push(MaterialPageRoute(
            //     builder: (_) =>
            //         HiddenDangerRectifyPage(hiddenDanger: hiddenDanger)));
          },
          text: '提交',
          textSize: 18,
          textColor: Color.fromARGB(255, 27, 130, 210),
        )
        // child: RaisedButton(
        //   color: Colors.white,
        //   onPressed: () {
        //     print('提交任务');
        //     _submit();
        //   },
        //   child: Text(
        //     '提交',
        //     style: TextStyle(
        //       color: Color.fromARGB(255, 27, 130, 210),
        //       fontSize: 18,
        //     ),
        //   ),
        // ),
        );
    // }
  }

  @override
  void initState() {
    super.initState();
    uploadAttachmentMethod.add(SelectionNode('uploadFile', '选择文件'));
    uploadAttachmentMethod.add(SelectionNode('takePhoto', '拍摄照片'));
    _controller = TextEditingController();
  }
}
